#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

void calculate_sha256(const char *filename, unsigned char *result) {
    SHA256_CTX ctx;
    unsigned char buffer[1024];
    size_t bytesRead;

    // 初始化SHA-256上下文
    SHA256_Init(&ctx);

    // 打开文件
    FILE *file = fopen(filename, "rb");
    if (file == NULL) {
        perror("Failed to open file");
        exit(EXIT_FAILURE);
    }

    // 读取文件并更新哈希
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
        SHA256_Update(&ctx, buffer, bytesRead);
    }

    // 计算最终哈希值
    SHA256_Final(result, &ctx);
    fclose(file);
}

void print_sha256(unsigned char *sha256) {
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        printf("%02x", sha256[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return EXIT_FAILURE;
    }

    unsigned char sha256[SHA256_DIGEST_LENGTH];
    calculate_sha256(argv[1], sha256);
    printf("SHA-256 hash of %s: ", argv[1]);
    print_sha256(sha256);

    return EXIT_SUCCESS;
}

